package com.beamfield.controller.manage;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author Zephyr
 * @Description:
 * @Date 2019/2/27
 */
@Controller
@RequestMapping("/cms/download")
public class DownloadController {

    @RequestMapping(value = "/android")
    @ResponseBody
    public String android(HttpServletResponse response){
        return downLoadFile(response, "梁场信息化管理平台-手机端", "android.zip");
    }


    @RequestMapping(value = "/pc")
    @ResponseBody
    public String pc(HttpServletResponse response){
        return downLoadFile(response, "梁场信息化管理平台-桌面端", "exe.zip");
    }

    private String downLoadFile(HttpServletResponse response, String zipName, String fileName){
        byte[] buff = new byte[2048];
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            File file = new File(this.getClass().getClassLoader().getResource("").getPath().replace("classes/","")+ fileName);
            if(file == null){
                return "下载失败";
            }
            InputStream in = new FileInputStream(file);
            response.setHeader("Content-Disposition", "attachment;fileName="+java.net.URLEncoder.encode(zipName, "UTF-8")+".zip");
            bis = new BufferedInputStream(in);
            bos = new BufferedOutputStream(response.getOutputStream());
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (bis != null)
                try {
                    bis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            if (bos != null)
                try {
                    bos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }
        return null;
    }
}
